﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using Microsoft.Phone.Controls;
using Renren.Helpers;
using System.Windows.Media;
using System.Device.Location;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Renren.Services;
using System;
using Microsoft.Phone.Shell;
using Renren.Models;

namespace Renren
{
    public partial class StatusPage : PhoneApplicationPage
    {
        private Brush defaultTextBoxBrush;
        private Brush defaultTextBlockBrush;
        private GeoCoordinateWatcher geoWatcher;
        private GeoCoordinate geoLocation;
        private const string defaultStatus = "你在干嘛？";
        private bool focused = false;
        private bool geoEnabled = false;

        public class EmotionLine
        {
            public string Item0 { get; set; }
            public string Item1 { get; set; }
            public string Item2 { get; set; }
            public string Item3 { get; set; }
            public string Item4 { get; set; }
            public string Item5 { get; set; }
            public string Item6 { get; set; }
        }

        public List<EmotionLine> EmotionList { get; set; }

        public StatusPage()
        {
            InitializeComponent();
            EmotionList = new List<EmotionLine>();
            FillEmotionList();
            DataContext = this;

            // Add location field tap event handler
            this.LocationField.Tap += (s, e) =>
                {
                    // Initialize geo watcher
                    if (geoWatcher == null)
                    {
                        geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                        geoWatcher.MovementThreshold = 20;

                        // Add geo status changed event handler
                        geoWatcher.StatusChanged += (gs, ge) =>
                            {
                                if (geoEnabled)
                                {
                                    switch (ge.Status)
                                    {
                                        case GeoPositionStatus.Disabled:
                                            this.LocationTextBlock.Text = "设备不支持";
                                            break;
                                        case GeoPositionStatus.Initializing:
                                            this.LocationTextBlock.Text = "初始化...";
                                            break;
                                        case GeoPositionStatus.NoData:
                                            this.LocationTextBlock.Text = "无法定位";
                                            break;
                                    }
                                }
                            };

                        // Add geo position changed event handler
                        geoWatcher.PositionChanged += (gs, ge) =>
                            {
                                geoLocation = ge.Position.Location;
                                DisplayLocation();
                            };

                        geoWatcher.Start();
                    }

                    // Toggle geo setting
                    geoEnabled = !geoEnabled;
                    if (geoEnabled)
                    {
                        DisplayLocation();
                        this.LocationTextBlock.Foreground = App.Current.Resources["PhoneAccentBrush"] as Brush;
                    }
                    else
                    {
                        this.LocationTextBlock.Text = "添加地点";
                        this.LocationTextBlock.Foreground = defaultTextBlockBrush;
                    }
                };

            this.TitleBlock.Loaded += (s, e) =>
                {
                    this.TitleBlock.Text = App.LoginUser.Name;
                };

            this.LocationTextBlock.Loaded += (s, e) =>
                {
                    defaultTextBlockBrush = this.LocationTextBlock.Foreground;
                };

            this.StatusBox.Loaded += (s, e) =>
                {
                    defaultTextBoxBrush = this.StatusBox.Foreground;
                };

            this.StatusBox.GotFocus += (s, e) =>
                {
                    focused = true;
                    if (this.StatusBox.Text == defaultStatus)
                    {
                        this.StatusBox.Text = string.Empty;
                    }
                    this.StatusBox.Foreground = new SolidColorBrush(Colors.Black);
                };

            this.StatusBox.LostFocus += (s, e) =>
                {
                    focused = false;
                    if (this.StatusBox.Text == string.Empty)
                    {
                        this.StatusBox.Text = defaultStatus;
                    }
                    this.StatusBox.Foreground = defaultTextBoxBrush;
                };

            this.StatusBox.TextChanged += (s, e) =>
                {
                    if (focused)
                    {
                        this.CharCounter.Text = StatusBox.Text.Length + "/240";
                    }
                };
        }

        private void FillEmotionList()
        {
            var list = Emotions.GetAllUri();
            for (int i = 0; i <= ((list.Count - 1) / 7); i++)
            {
                EmotionList.Add(new EmotionLine());
                EmotionList[i].Item0 = (i * 7 + 0) < list.Count ? list[i * 7 + 0] : string.Empty;
                EmotionList[i].Item1 = (i * 7 + 1) < list.Count ? list[i * 7 + 1] : string.Empty;
                EmotionList[i].Item2 = (i * 7 + 2) < list.Count ? list[i * 7 + 2] : string.Empty;
                EmotionList[i].Item3 = (i * 7 + 3) < list.Count ? list[i * 7 + 3] : string.Empty;
                EmotionList[i].Item4 = (i * 7 + 4) < list.Count ? list[i * 7 + 4] : string.Empty;
                EmotionList[i].Item5 = (i * 7 + 5) < list.Count ? list[i * 7 + 5] : string.Empty;
                EmotionList[i].Item6 = (i * 7 + 6) < list.Count ? list[i * 7 + 6] : string.Empty;
            }
        }

        private void DisplayLocation()
        {
            if (geoEnabled && geoLocation != null)
            {
                this.LocationTextBlock.Text =
                    geoLocation.Latitude.ToString("0.0") +
                    " " +
                    geoLocation.Longitude.ToString("0.0");
            }
        }

        private void Emotion_Tap(object sender, GestureEventArgs e)
        {
            var token = Emotions.GetStatus(((sender as Image).Source as BitmapImage).UriSource.ToString());
            if (this.StatusBox.Text == defaultStatus)
            {
                this.StatusBox.Text = token;
            }
            else
            {
                this.StatusBox.Text += token;
            }
        }

        private void Publish_Clicked(object sender, EventArgs e)
        {
            this.TitleBlock.Text = "正在更新...";
            StatusService.PublishStatus(
                this.StatusBox.Text,
                () =>
                {
                    this.TitleBlock.Text = "更新成功!";
                });
        }

        private void EmotionButton_Clicked(object sender, EventArgs e)
        {
            if (this.EmotionPanel.Visibility == Visibility.Collapsed)
            {
                this.EmotionPanel.Visibility = Visibility.Visible;
            }
            else if (this.EmotionPanel.Visibility == Visibility.Visible)
            {
                this.EmotionPanel.Visibility = Visibility.Collapsed;
            }
        }

        private void FriendButton_Clicked(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/FriendPickerPage.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var selectedFriendKey = "SelectedFriend";
            var state = PhoneApplicationService.Current.State;
            if (state.Keys.Contains(selectedFriendKey) && state[selectedFriendKey] != null)
            {
                var friend = (FriendModel)state[selectedFriendKey];
                var atFriend = "@" + friend.Name + "(" + friend.UserId + ") ";
                if (this.StatusBox.Text == defaultStatus)
                {
                    this.StatusBox.Text = atFriend;
                }
                else
                {
                    this.StatusBox.Text += atFriend;
                }
                state[selectedFriendKey] = null;
            }
        }
    }
}